﻿namespace GuaHao
{
    public partial class FormUser : Form
    {
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", "data_user.txt");
        List<User> users = new List<User>();
        public FormUser()
        {
            InitializeComponent();
            dataGridViewUser.CellFormatting += DataGridViewUser_CellFormatting;
        }
        private void DataGridViewUser_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 判断是否是密码列（这里假设密码列的列名为"密码"，你可根据实际情况调整）
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && dataGridViewUser.Columns[e.ColumnIndex].Name == "密码")
            {
                if (e.Value != null)
                {
                    // 将单元格的值替换为对应长度的*号字符串
                    e.Value = new string('*', e.Value.ToString().Length);
                }
            }
        }
        private void FormUser_Load(object sender, EventArgs e)
        {
            users = TextJson.ReadUser(path);
            dataGridViewUser.DataSource = users;
        }
        private int currentRowIndex = -1;
        private int currentUserId = -1;
        /// <summary>
        /// 文本框赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridViewUser_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            textBoxUserName.Clear();
            textBoxName.Clear();
            textBoxPassWord.Clear();
            comboBoxRole.Text = "";
            stateboBox.Text = "";
            // 判断是否点击了有效的单元格（避免点击表头空白处等无效情况）
            if (e.RowIndex > -1)
            {
                if (dataGridViewUser.Rows[e.RowIndex].DataBoundItem is User user)
                {
                    textBoxUserName.Text = user.UserName.ToString();
                    textBoxName.Text = user.Name.ToString();
                    textBoxPassWord.Text = user.Password.ToString();
                    comboBoxRole.Text = user.Role.ToString();
                    stateboBox.Text = user.State.ToString();
                    currentUserId = Convert.ToInt32(user.Id.ToString()); // 获取并记录当前行对应的用户ID
                }
                currentRowIndex = e.RowIndex;
            }
        }
        /// <summary>
        /// 新增用户和修改用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Savebutton_Click(object sender, EventArgs e)
        {
            string name = textBoxName.Text;
            string username = textBoxUserName.Text;
            string password = textBoxPassWord.Text;
            string role = comboBoxRole.Text;
            string state = stateboBox.Text;
            if (username == "")
            {
                MessageBox.Show("账号不能为空，请填写！");
                return;
            }

            if (password == "")
            {
                MessageBox.Show("密码不能为空，请填写！");
                return;
            }

            if (name == "")
            {
                MessageBox.Show("用户名不能为空，请填写！");
                return;
            }

            if (role == "")
            {
                MessageBox.Show("角色不能为空，请填写！");
                return;
            }
            if (state == "")
            {
                MessageBox.Show("账号状态不能为空，请填写！");
                return;
            }

            if (currentRowIndex < users.Count && currentRowIndex > -1)
            {
                User userToModify = users[currentRowIndex];
                userToModify.Name = name;
                userToModify.UserName = username;
                userToModify.Password = MD5Encrypt.MD5Encrypt16(password);
                userToModify.Role = role;
                userToModify.State = state;
                // 将更新后的列表重新保存（序列化）到文件等
                TextJson.WriteUser(users, path);
                // 重新刷新表格数据
                dataGridViewUser.DataSource = null;
                dataGridViewUser.DataSource = users;
                MessageBox.Show("修改成功", "修改", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //自增加Id值
                int maxID = users.Max(u => u.Id) + 1;
                // 创建新的User对象
                User newUser = new User
                {
                    Id = maxID,
                    Name = textBoxName.Text,
                    UserName = textBoxUserName.Text,
                    Password = MD5Encrypt.MD5Encrypt16(password),
                    Role = role,
                    State = state
                };
                // 将新用户添加到列表
                users.Add(newUser);
                TextJson.WriteUser(users, path);
                dataGridViewUser.DataSource = null;
                dataGridViewUser.DataSource = users;
            }
        }
        /// <summary>
        /// 密码重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Deletebutton_Click(object sender, EventArgs e)
        {
            //if (currentRowIndex >= 0 && users != null && currentRowIndex < users.Count)
            //{
            //    DialogResult result = MessageBox.Show("是否确认删除？", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            //    if (result == DialogResult.Yes)
            //    {
            //        // 用户点击了“是”按钮，执行删除操作
            //        users.RemoveAll(u => u.Id == currentUserId);
            //        TextJson.WriteUser(users, path);
            //        LoadUser(users);
            //    }
            //}
            //else
            //{
            //    MessageBox.Show("未找到该用户");
            //}
            if (currentRowIndex >= 0 && users != null && currentRowIndex < users.Count)
            {
                DialogResult result = MessageBox.Show("是否确认重置？(重置密码为默认123)", "密码重置", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    // 用户点击了“是”按钮，执行重置操作
                    foreach (User user in users)
                    {
                        if (user.Id == currentUserId)
                        {
                            user.Password = MD5Encrypt.MD5Encrypt16("123");
                        }
                    }
                    TextJson.WriteUser(users, path);
                    dataGridViewUser.DataSource = null;
                    dataGridViewUser.DataSource = users;
                }
            }
            else
            {
                MessageBox.Show("未找到该用户");
            }
        }
        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Querybutton_Click(object sender, EventArgs e)
        {
            List<User> filteredUsers = new List<User>();
            string query = querytextbox.Text;
            if (query != "")
            {
                foreach (User user in users)
                {
                    if (user.Name.Contains(query) || user.UserName.Contains(query) || user.Role.Contains(query))
                    {
                        filteredUsers.Add(user);
                    }
                }
                if (filteredUsers.Count < 1)
                {
                    MessageBox.Show("未查询到该用户");
                }
                else
                {
                    dataGridViewUser.DataSource = filteredUsers;
                }
            }
            else
            {
                dataGridViewUser.DataSource = users;
            }
        }

        
    }
}